package com.heima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.domain.Patient;
import com.heima.mapper.PatientMapper;
import com.heima.service.IPatientService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.thread.UserThreadLocal;
import com.heima.vo.CommonResult;
import com.heima.vo.PatientIdVO;
import com.heima.vo.PatientVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 就诊人 服务实现类
 * </p>
 *
 * @author wangjiexin
 * @since 2023-01-29
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements IPatientService {

    @Autowired
    PatientMapper patientMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<PatientVO> getlist() {
        //获取当前线程的用户id
        String userId = UserThreadLocal.get();
        //现去redis缓存查询看看有没有数据
        String patients = redisTemplate.opsForValue().get("patientList:user_" + userId);
        //如果有数据直接返回，不要访问myqsl
        if (StringUtils.isNotEmpty(patients)) {
            //因为进来的数据是json类型 所以要转换一下类型
            List<PatientVO> list = JSON.parseArray(patients, PatientVO.class);
            //这边可以内联变量，不过为了方便查看 ，不做内联
            return list;
        }


        //查询就诊人列表,返回的是一个列表
        ArrayList<PatientVO> user = new ArrayList<>();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        //查询就诊人id和是否默认的值，进行升序排列
        wrapper.eq(Patient::getUserId, userId);
        wrapper.orderByDesc(Patient::getIsDefault);
        //然后去查询一下
        List<Patient> list = patientMapper.selectList(wrapper);
        //判断是否不为空 isEmpty是 为空 的意思
        if (!CollectionUtil.isEmpty(list)) {
            for (Patient patient : list) {
                if (patient == null) {
                    //如果查询到的值为空那么就跳过
                    continue;
                }
                //把vo new出来
                PatientVO vo = new PatientVO();
                //把数据源复制一份
                BeanUtils.copyProperties(patient, vo);
                String cardNumber = patient.getCardNumber();
                Integer cardType = patient.getCardType();
                //判断一下身份证类型,0为身份证 1为护照
                if (cardType == 0) {
                    //身份证进行脱敏操,调用糊涂工具类
                    vo.setCardNumber(DesensitizedUtil.idCardNum(cardNumber, 4, 4));

                }
                //然后把查询出来的数据写到集合里面
                user.add(vo);

            }
        }
        //把查询出来的数据写入到redis里面
        redisTemplate.opsForValue().set("patientList:user_" + userId, JSON.toJSONString(user));


        return user;
    }

    @Override
    public Boolean add(Patient patient) {
        //新增和修改
        if (patient == null) {
            throw new RuntimeException("入参不能为空~！");
        }
        //先查询。如果存在 那么就进入修改，如果不存在，那就进入添加
        //通过身份证查询
        String number = patient.getCardNumber();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getCardNumber, number);
        Patient one = patientMapper.selectOne(wrapper);
        if (one == null) {
            //添加
            int res = patientMapper.insert(patient);
            if (res != 1) {
                throw new RuntimeException("添加就诊人失败~！！");
            }
            return res > 0;
        }
        //如果不为空，那就走修改
        int update = patientMapper.update(patient, wrapper);
        if (update != 1) {
            throw new RuntimeException("修改就诊人失败~！");
        }
        return update >= 0;
    }

    @Override
    public PatientIdVO selectById(Integer patientId) {
        if (patientId==null){
            throw new RuntimeException("入参不能为空~！");
        }
        Patient patient = patientMapper.selectById(patientId);
        PatientIdVO vo=new PatientIdVO();
        BeanUtils.copyProperties(patient,vo);

        return vo;
    }

    @Override
    public Boolean delById(Integer patientId) {
        //获取当前线程的用户id
        String userId = UserThreadLocal.get();
        //通过id 删除就诊人
        if (patientId==null){
            throw new RuntimeException("入参不能为空~！！");
        }
        int res = patientMapper.deleteById(patientId);
        if (res!=1){
            throw new RuntimeException("删除就诊人失败~！");
        }
        //这边需要把redis缓存给删了
        redisTemplate.delete("patientList:user_" + userId);

        return res>=0;
    }
}
